package com.dahua.ui.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.dahua.R;
import com.dahua.ui.base.BaseActivity;
import com.dahua.ui.user.LoginAct;
import com.dahua.utils.AppApplication;
import com.dahua.utils.DownPicUtil;
import com.dahua.utils.ToastUtils;
import com.dahua.utils.UserPreference;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Locale;

import io.reactivex.functions.Consumer;


/**
 *
 */
public class TotalNumAct extends BaseActivity implements
        OnDismissListener {

    public WebView webView;
    private String url;
    private Context context;

    public static TotalNumAct instance;

    public static TotalNumAct getInstance() {
        return instance;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.totalnum_act);
        instance = this;
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

private TextView text_upload_title;

    @SuppressLint("JavascriptInterface")
    private void init() {
        showLoadingDialog();
        url = "file:///android_asset/part2/views/integral/myPointsApp.html";
        context = TotalNumAct.this;
        text_upload_title = findViewById(R.id.text_upload_title);

        webView = (WebView) findViewById(R.id.fu_webview);
        // 启用数据库
        webView.getSettings().setDatabaseEnabled(true);
        String dir = this.getApplicationContext()
                .getDir("database", Context.MODE_PRIVATE).getPath();
        // 设置定位的数据库路径
        webView.getSettings().setGeolocationDatabasePath(dir);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);// 设置可以访问文件
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
//		webView.getSettings().setPluginsEnabled(true);// 支持插件
        webView.getSettings().setDomStorageEnabled(true);// 定位相关
        webView.getSettings().setGeolocationEnabled(true); // 启用定位
        webView.getSettings().setCacheMode(webView.getSettings().LOAD_NO_CACHE); // 不使用缓存
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);// 支持通过JS打开新窗口
        webView.addJavascriptInterface(new ShopJavaScriptInterface(), "demo");
        webView.requestFocus();
//        setCookie();
        webView.loadUrl(url);
        webView.setWebViewClient(new WebViewClient() {
            // 当点击链接时,希望覆盖而不是打开新窗口
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("dahua://back")) {
                    if (webView.canGoBack()) {
                        webView.goBack();
                    } else {
                        finish();
                        AppApplication.aliveActivitys.remove(AppApplication.aliveActivitys.size() - 1);
                    }
                    return true;
                } else if (url.contains("dahua://home")) {
                    finish();
                    AppApplication.aliveActivitys.remove(AppApplication.aliveActivitys.size() - 1);
                    return true;
                } else if (url.contains("dahua://logout")) {
                    logout();
                    return true;
                } else if (url.contains("dahua://scan")) {
                    requestPermission();
                    return true;
                } else if (url.contains("dahua://login")) {
                    if(url.contains("email")){
                        String params = url.substring("dahua://login?".length(),url.length());
                        String[] p = params.split("&&");
                        String tempStr ="";
                        try {
                            tempStr= URLDecoder.decode(p[0].substring("email=".length(),p[0].length()),"utf-8");
                        } catch (UnsupportedEncodingException e) {
                            tempStr = p[0].substring("email=".length(),p[0].length());
                        }

                        UserPreference.getInstance(getApplicationContext()).setLogonId(tempStr);
                        startActivityForResult(new Intent(getApplicationContext(), LoginAct.class), 2);//lzh
                    }else{
                        startActivityForResult(new Intent(getApplicationContext(), LoginAct.class), 2);//lzh
                    }

                    return true;
                } else if (url.contains("dahua://registerBack")) {
                    webView.loadUrl("javascript:logon('" + UserPreference.getInstance(getApplicationContext()).getUid() + "')");
                    webView.loadUrl("javascript:reload()");
                    finish();
                    AppApplication.aliveActivitys.remove(AppApplication.aliveActivitys.size() - 1);
                    return true;
                } else if (url.contains("dahua://nativeback")) {
                    finish();
                    return true;
                } else if (url.contains("dahua://openweb")) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(url.substring("dahua://openweb?".length()));
                    intent.setData(content_url);
                    startActivity(intent);
                    return true;
                }else if(url.contains("dahua://openShare")){
                    shareToWhatsApp(url);
                    return true;
                }else if(url.contains("dahua://header")){
                    String params = url.substring("dahua://header?".length(),url.length());
                    String[] p = params.split("&&");
                    String tempStr ="";
                    try {
                        tempStr= URLDecoder.decode(p[0].substring("title=".length(),p[0].length()),"utf-8");
                    } catch (UnsupportedEncodingException e) {
                        tempStr = p[0].substring("title=".length(),p[0].length());
                    }
                    text_upload_title.setText(tempStr);
                    return true;
                } else if (url.contains("dahua://langSwitching")) {
                    String params = url.substring("dahua://langSwitching?".length(),url.length());
                    String[] p = params.split("&&");
                    String tempStr ="";
                    try {
                        tempStr= URLDecoder.decode(p[0].substring("lang=".length(),p[0].length()),"utf-8");
                    } catch (UnsupportedEncodingException e) {
                        tempStr = p[0].substring("lang=".length(),p[0].length());
                    }
                    UserPreference.getInstance(TotalNumAct.this).setLang(tempStr);
                    Log.e("tempStr:",tempStr);
                    return true;
                }
                view.loadUrl(url);
                return true; // 返回true,代表事件已处理,事件流到此终止
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            // 当WebView进度改变时更新窗口进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // Activity的进度范围在0到10000之间,所以这里要乘以100
                if (newProgress == 100) {
                    hideLoadingDialog();
                }

            }

            // 定位
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin,
                                                           GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }

            @Override
            // call when javascript request a popup window
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                return true;
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                TotalNumAct.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                TotalNumAct.this.startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                TotalNumAct.this.startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 5.0+
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
                return true;
            }


        });
        webView.setDownloadListener(new DownloadListener() {


            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                // TODO Auto-generated method stub
                Log.i("tag", "url=" + url);
                Log.i("tag", "userAgent=" + userAgent);
                Log.i("tag", "contentDisposition=" + contentDisposition);
                Log.i("tag", "mimetype=" + mimetype);
                Log.i("tag", "contentLength=" + contentLength);
                // download(url);
                // startService();
                // Uri uri = Uri.parse(url);
                // Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                // startActivity(intent);
            }
        });
    }

    private ValueCallback<Uri> mUploadMessage;
    private int FILECHOOSER_RESULTCODE = 9000;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }else  if (requestCode == 2) {// 传userid
            webView.loadUrl("javascript:logon('" + UserPreference.getInstance(getApplicationContext()).getUid() + "')");
            webView.loadUrl("javascript:reload()");
        }
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }

    private ValueCallback<Uri[]> mUploadCallbackAboveL;

    public void logout() {
        UserPreference.getInstance(getApplication()).setLogin(false);
        UserPreference.getInstance(getApplication()).setUid("");
        UserPreference.getInstance(getApplication()).setName("");
        UserPreference.getInstance(getApplication()).setCountryId("");
//                    UserPreference.getInstance(getApplication()).setLogonId("");
        UserPreference.getInstance(getApplication()).setRole("");
        UserPreference.getInstance(getApplication()).setStatus("");
        UserPreference.getInstance(getApplicationContext()).setPwd("");
        UserPreference.getInstance(getApplicationContext()).setData("");
        webView.loadUrl("javascript:logout()");

//                    AppApplication.aliveActivitys.remove(AppApplication.aliveActivitys.size()-2);
//                    JPushInterface.stopPush(getApplicationContext());
//                    startActivity(new Intent(getApplicationContext(), LoginAct.class));

    }

    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;

    }

    private boolean isZh() {
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        if (language.endsWith("zh"))
            return true;
        else
            return false;
    }

    final class ShopJavaScriptInterface {

        ShopJavaScriptInterface() {
        }

        @JavascriptInterface
        public void JavacallHtml() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //id#name#role#logonId#countryId

                    if (UserPreference.getInstance(getApplicationContext()).isLogin()) {
                        webView.loadUrl("javascript: getContext('" + UserPreference.getInstance(getApplicationContext()).getUid() + "#" + UserPreference.getInstance(getApplicationContext()).getName()
                                + "#" + UserPreference.getInstance(getApplicationContext()).getRole() + "#" + UserPreference.getInstance(getApplicationContext()).getLogonId() + "#" + UserPreference.getInstance(getApplicationContext()).getCountryId() + "')");
                    } else {
                        webView.loadUrl("javascript: getContext('" + "" + "#" + "" + "#" + "" + "#" + "" + "#" + "" + "')");
                    }
//                    webView.loadUrl("javascript: showFromHtml()");
//                    showToast("的顶顶顶顶顶");
                }
            });
        }
    }

    public void refresh(View view) {
        if (!"".equals(webView.getUrl()) && webView.getUrl() != null) {
            webView.loadUrl(webView.getUrl());
        }
    }

    public void back(View view) {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
        finish();
      }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if(url.contains("views/product/category.html")) {
//                exit();
//            } else {
            if (webView.canGoBack()/* && success*/) {
                webView.goBack(); // goBack()表示返回webView的上一页面
            } else {
                finish();
            }
//            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {

    }
    /**
     *
     * @param url dahua://openShare?text=IPC-HDBW8331E-Z(3MP WDR IR Dome Network Camera)
     *               &&img=http://app.dahuasecurity.com/img/product/bbf4adbc-3f05-4287-ba19-bd899667b5e2.png
     */
    private void shareToWhatsApp(String url) {

        if(!isPackageInstalled("com.whatsapp",this)){
            Toast.makeText(this,"Whatsapp have not been installed.",Toast.LENGTH_SHORT).show();
            return;
        }
        if(url.contains("&&img")){
            //share img
            Log.i("TAG",url);
            String params = url.substring("dahua://openShare?".length(),url.length());
            String[] p = params.split("&&");
            String tempStr ="";
            try {
                tempStr= URLDecoder.decode(p[0].substring("text=".length(),p[0].length()),"utf-8");
            } catch (UnsupportedEncodingException e) {
                tempStr = p[0].substring("text=".length(),p[0].length());
            }
            final String text = tempStr;
            String imgUrl = p[1].substring("img=".length(),p[1].length());
            String imgName = imgUrl.substring(imgUrl.lastIndexOf("/"),imgUrl.length());

            DownPicUtil.downPic(this, imgUrl, imgName, new DownPicUtil.DownFinishListener() {
                @Override
                public void getDownPath(String filePath) {
                    if(TextUtils.isEmpty(filePath)){
                        ToastUtils.showToast(TotalNumAct.this,"DownLoad pic failed! Share Fail");
                        return;
                    }
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    //Target whatsapp:
                    shareIntent.setPackage("com.whatsapp");
                    //Add text and then Image URI
                    shareIntent.putExtra(Intent.EXTRA_TEXT, text);
                    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(filePath));
                    shareIntent.setType("image/jpeg");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    startActivity(shareIntent);
                }
            });

        }else{
            //share text
            Log.i("TAG",url);
            String params = url.substring("dahua://openShare?".length(),url.length());
            String text = "";
            try {
                text = URLDecoder.decode(params.substring("text=".length(),params.length()),"utf-8");
            } catch (UnsupportedEncodingException e) {
                text = params.substring("text=".length(),params.length());
            }
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            //Target whatsapp:
            shareIntent.setPackage("com.whatsapp");

            shareIntent.putExtra(Intent.EXTRA_TEXT, text);
            shareIntent.setType("text/plain");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(shareIntent);
        }



        /**
         * Show share dialog BOTH image and text
         */
//        File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "yodo1_poster.jpg");
//        Uri imageUri = Uri.parse(f.getAbsolutePath());
//        Intent shareIntent = new Intent();
//        shareIntent.setAction(Intent.ACTION_SEND);
//        //Target whatsapp:
//        shareIntent.setPackage("com.whatsapp");
//        //Add text and then Image URI
//        shareIntent.putExtra(Intent.EXTRA_TEXT, text);
//        shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
//        shareIntent.setType("image/jpeg");
//        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//        startActivity(shareIntent);

//        Bitmap adv = BitmapFactory.decodeResource(getResources(), R.mipmap.system_message);
//        Intent share = new Intent(Intent.ACTION_SEND);
//        share.setType("image/jpeg");
//        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//        adv.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//        File f = new File(Environment.getExternalStorageDirectory()
//                + File.separator + "trimedcard.jpg");
//        try {
//            f.createNewFile();
//            new FileOutputStream(f).write(bytes.toByteArray());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        share.putExtra(Intent.EXTRA_TEXT, "this is text");
//        share.putExtra(Intent.EXTRA_STREAM,
//                Uri.parse( Environment.getExternalStorageDirectory()+ File.separator+"trimedcard.jpg"));
//        if(isPackageInstalled("com.whatsapp",this)){
//            share.setPackage("com.whatsapp");
//            startActivity(Intent.createChooser(share, "Share Image"));
//
//        }else{
//            Toast.makeText(getApplicationContext(), "Please Install Whatsapp", Toast.LENGTH_LONG).show();
//        }

    }


    private boolean isPackageInstalled(String packagename, Context context) {
        PackageManager pm = context.getPackageManager();
        try {
            pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    private void requestPermission(){
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEach(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted){ //允许
                            startActivity(new Intent(getApplicationContext(), MipcaActivityCaptureZbar.class));//lzh
                        }else if (permission.shouldShowRequestPermissionRationale){//拒绝,期待下次询问
                            Toast.makeText(TotalNumAct.this, "This function cannot be used", Toast.LENGTH_SHORT).show();
                        }else {//拒绝,自行去设置界面
                            AlertDialog.Builder builder = new AlertDialog.Builder(TotalNumAct.this);
                            builder.setTitle(" warning");
                            builder.setMessage("The user has rejected the permission and cannot use this function. Do you want to jump to the setting interface?");

                            // 拒绝, 退出应用
                            builder.setNegativeButton("cancel",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    });

                            builder.setPositiveButton("go to settings",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(
                                                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            intent.setData(Uri.parse("package:" + getPackageName()));
                                            startActivityForResult(intent, 444);
                                        }
                                    });

                            builder.setCancelable(false);

                            builder.show();
                        }

                    }
                });
    }

}
